import { defineStore } from 'pinia'
import cache from '@/utils/cache'
import { login, logout, getUserInfo } from '@/api/auth'

export const useUserStore = defineStore('userStore', {
  state: () => ({
    // 登录token
    token: cache.getToken(),
    // 刷新token
    refreshToken: cache.getRefreshToken(),
    // 登录用户信息
    user: {
      id: '',
      userName: '',
      nickName: '',
      email: '',
      phone: '',
      permissions: [], // 权限列表
      roles: [] // 角色列表
    },
    // 企业标识
    companyIdentity: 'demo',
    // 视频流ip地址
    rtcIP: ''
  }),
  actions: {
    setUser(val: any) {
      this.user = val
    },
    setToken(val: string) {
      this.token = val
      cache.setToken(val)
    },
    setRefreshToken(val: string) {
      this.refreshToken = val
      cache.setRefreshToken(val)
    },
    setCompanyIdentity(val: string) {
      this.companyIdentity = val
    },
    setRtcIP(val: string) {
      this.rtcIP = val
    },
    // 用户登录
    async loginAction(loginForm: any) {
      const {
        data: { access_token, refreshToken }
      } = await login(loginForm)
      this.setToken(access_token)
      this.setRefreshToken(refreshToken)
    },
    // 获取用户信息
    async getUserInfoAction() {
      const { data } = await getUserInfo()
      // const { data: rtcIP } = await getRtcIP()
      this.setUser(data)
      // this.setRtcIP(rtcIP)
      // 企业标识
      // const { data: companyIdentity } = await getCompanyIdentity()
      // this.setCompanyIdentity(companyIdentity)
    },
    // 用户退出
    async logoutAction() {
      await logout()
      this.setToken('')
      this.setRefreshToken('')
      // 刷新页面
      window.location.reload()
    }
  }
})
